<?php
namespace App\Admin\Controllers;
use App\Admin\Models\Adminusers;
use App\Admin\Models\AdminUserToken;
use Common\ControllerAdBase;
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;
use Phalcon\Session;
use Phalcon\Http\Request;
class UserController extends ControllerAdBase
{

    public function initialize()
    {
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Methods:POST,GET');
        header('Access-Control-Allow-Headers:x-requested-with, content-type');
    }


    /**
     * 后台登录
     */
    public function loginAction(){
        $request = $this->request;
        if($request->isPost()){
            $params = file_get_contents('php://input');
            $params = json_decode($params,true);
            if(!isset($params['username']) || empty($params['username'])){
                $this->fail(-1,'用户名不能为空');
            }
            if(!isset($params['password']) || empty($params['password'])){
                $this->fail(-1,'密码不能为空');
            }
            if(!isset($params['verifycode']) || empty($params['verifycode'])){
                $this->fail(-1,'验证码不能为空');
            }
            $adminuser = new Adminusers();
            $user = $adminuser->find_by_name($params['username']);
            if($user['status'] == 2){
                $this->fail(-1,'该账号已经被禁止登陆');
            }
            if(empty($user)) {
                $this->fail(-1, '管理员不存在');
            }
//            $toolsAuthenticator = new ToolsAuthenticator();
//            $verifycode = $toolsAuthenticator->verifyCode($user['google_vercode'],$params['verifycode']);
//            if(!$verifycode){
//                $this->fail(-1,'验证码输入错误');
//            }


            if(md5($params['password']) != $user['password'])
                return $this->fail(-1, '账号或密码错误');
            //生成Token
            $token = ToolsController::MakeToken($user['id']);
            $has = $adminuser->find_by_firstId($user['id']);
            if(empty($has)){
                //没有找到人
            } else {
                $admin_user_token = new AdminUserToken();
                $admin_arr = $admin_user_token->find_by_firstAdminId($user['id']);
                if(empty($admin_arr)){
                    $admin_arr['admin_id']=$user['id'];
                }
                $admin_arr['token'] = $token;
                $admin_arr['expiretime'] = date('Y-m-d H:i:s',((3600 * ToolsController::EXPIRE_HOUR) + time()));
                $admin_arr['flushtime'] = time();
                $res = $admin_user_token->save_user($admin_arr);
            }
            if(empty($res)) return $this->fail(-1,'登录失败，请稍后再试');
            //Token加密
            $encryptToken = ToolsController::TokenEncrypt($user['id'], $token);
            $this->ok(['Token'=>$encryptToken],20000,'登录成功');
        }
    }
}
